//
//  XKContentView.swift
//  XKPageView
//
//  Created by 徐凯 on 2017/6/6.
//  Copyright © 2017年 XK. All rights reserved.
//

import UIKit

/*
    self. 
    1.如果有歧义不能省
    2.闭包里不能省
 */

private let ID = "ContentCell"

class XKContentView: UIView{
    
    // MARK:- 属性
    fileprivate var childVCs : [UIViewController]
    fileprivate var parentVC : UIViewController
    fileprivate lazy var collectionView : UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        let collectionView =  UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ID)
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = false
        collectionView.scrollsToTop = false
        return collectionView
    }()
    

    // MARK:- 构造函数
    init(frame: CGRect, childVCs : [UIViewController], parentVC : UIViewController) {
        

        self.childVCs = childVCs
        self.parentVC = parentVC;
        super.init(frame: frame)
        
        setupUI()
        
       
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   

}


extension XKContentView
{
    fileprivate func setupUI()
    {
        for childVc in childVCs
        {
            parentVC.addChildViewController(childVc)
        }
        
        addSubview(collectionView)
    }
}

// MARK:- UICollectionViewDataSource,UICollectionViewDataSource
extension XKContentView : UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVCs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ID, for: indexPath)
        
        // 添加view
        // 将之前的View删除
        for subview in cell.contentView.subviews
        {
            subview.removeFromSuperview()
        }
        
        let childVc = childVCs[indexPath.item]
        cell.contentView.addSubview(childVc.view)
        
        return cell
    }
}

extension XKContentView : UICollectionViewDelegate
{
    
}
